package ch.fusun.baron.city.ui;

import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;

import ch.fusun.baron.city.City;
import ch.fusun.baron.city.api.CityService;
import ch.fusun.baron.core.injection.Inject;
import ch.fusun.baron.data.DataListener;
import ch.fusun.baron.data.DataUpdate;
import ch.fusun.baron.map.Tile;
import ch.fusun.baron.map.ui.gef.editpart.TileChild;
import ch.fusun.baron.map.ui.gef.editpart.TileChildrenProvider;
import ch.fusun.baron.player.Dynasty;
import ch.fusun.baron.player.Player;
import ch.fusun.baron.player.api.Country;
import ch.fusun.baron.player.api.PlayerService;
import ch.fusun.baron.property.api.PropertyService;

/**
 * Adds a little flag to the city, corresponding to the coat of arms of the
 * dynasty
 */
public class CityDynastyTileChildrenProvider implements TileChildrenProvider {

	private final transient List<DataListener> listeners = new LinkedList<DataListener>();
	private transient CityService cityService;
	@Inject
	private transient PropertyService propertyService;
	@Inject
	private transient PlayerService playerService;

	/**
	 * Injection constructor
	 */
	public CityDynastyTileChildrenProvider() {
	}

	/**
	 * @param cityService
	 *            The injected service
	 */
	@Inject
	public void setCityService(CityService cityService) {
		this.cityService = cityService;
		this.cityService.addDataListener(this);
	}

	@SuppressWarnings("rawtypes")
	@Override
	public Collection<TileChild> getChildren(Tile tile) {
		City city = cityService.getCity(tile);
		Collection<TileChild> children = new ArrayList<TileChild>();
		Country country = (Country) propertyService.getOwnership(tile);
		Dynasty dynasty = playerService.getDynasty((Player) propertyService
				.getOwnership(country));
		if (city != null) {
			children.add(new CityDynastyTileChild(dynasty));
		}
		return children;
	}

	@Override
	public void addListener(DataListener listener) {
		this.listeners.add(listener);
	}

	@Override
	public void dataChanged(DataUpdate update) {
		for (DataListener listener : listeners) {
			listener.dataChanged(update);
		}
	}
}
